import request from '@/utils/request.js'
import config from '@/utils/config/index.js'
import project from '@/utils/config/project.js'
import { Base64 } from 'js-base64'

/**
 * 获取验证码
 */
export async function getCaptcha(params) {
	let result = await uni.request({
		url: config.baseUrl + '/oauth2/v3/user/captcha',
		data: params,
		method: 'GET'
	})
	if(result[1]) {
		return result[1].data
	} else {
		uni.showToast({
		    title: '网络异常，请稍后重试',
		    icon: 'none'
		});
		return
	}
}

/**
 * 登录验证
 */
export function validateLogin(params) {
	params.appKey = project.SSO_APP_KEY
	params.appSecret = project.SSO_APP_SECRET
	params.keyId = project.SSO_KEY_ID
	
	return request.post({
		url: '/userInterface/v3/api/developer/login/validateLogin',
		params,
		paramType: 'post',
		loading: false
	});
}

/**
 * 登录
 */
export function login(params) {
	// params.password = Base64.encode(params.password)
	return request.post({
		url: '/oauth2/v3/user/login/apply',
		params,
		paramType: 'post',
		loading: false
	});
}

/**
 * 单点登录
 */
export function loginSSO(params) {
	params.password = Base64.encode(params.password)
	return request.post({
		url: '/oauth2/v3/user/login/applySSO',
		params,
		paramType: 'post',
		loading: false
	});
}

/**
 * 申请授权
 */
export function authorize(loginState) {
	const params = {
		client_id: config.APP_CLIENT_ID,
		login_state: loginState
	}
	return request.post({
		url: '/oauth2/v3/authorize/apply',
		params: params,
		paramType: 'post',
		loading: false
	});
}

/**
 * 申请access_token
 */
export function accessToken(params) {
	return request.post({
		url: '/oauth2/v3/authentication/apply',
		params,
		paramType: 'post',
		loading: false
	});
}

/**
 * 用户上下文信息
 */
export function getUserInfoByName(username) {
	const params = {
		username
	}
	return request.post({
		url: '/oauth2/v3/user/context',
		params,
		loading: false
	});
}

/**
 * 登出
 */
export function logout() {
	const params = {
		access_token: uni.getStorageSync("_app_token")
	}
	return request.post({
		url: '/oauth2/v3/user/logout',
		params,
		loading: false
	});
}